package com.act.moudles.user.service.impl;


import com.act.components.UserComponent;
import com.act.constant.LoginTypeEnums;
import com.act.constant.UserTypeEnums;
import com.act.moudles.user.dao.ComboDetailDao;
import com.act.moudles.user.dao.MenuDao;
import com.act.moudles.user.dao.ComboDao;
import com.act.moudles.user.entity.ComboDetail;
import com.act.moudles.user.entity.Menu;
import com.act.moudles.user.entity.ComBo;
import com.act.moudles.user.pojo.ComboPojo;
import com.act.moudles.user.service.ComboService;
import com.act.utils.SplitUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class ComboServiceImpl extends ServiceImpl<ComboDao, ComBo> implements ComboService {

    @Resource
    private MenuDao menuDao;

    @Resource
    private ComboDetailDao comboDetailDao;

    @Resource
    private UserComponent userComponent;

    @Override
    public IPage<ComBo> pageTemp(IPage<ComBo> page, ComBo comBo) {
        IPage<ComBo>  iPage =  page(page,comBo.buildQuery());
        iPage.setRecords(compliteCount(iPage.getRecords()));
        return iPage;
    }



    @Override
    public String addTemp(ComboPojo refMenuTempPojo) {
        String checkRes = checkUnion(refMenuTempPojo);
        if(StringUtils.isNotEmpty(checkRes)){
            return checkRes;
        }
        if(CollectionUtils.isEmpty(refMenuTempPojo.getMenuIdList())){
            return "未配置菜单";
        }
        //新增套餐
        ComBo comBo = refMenuTempPojo.pojoTo();
        comBo.setDelFlag(1);
        comBo.setCreateTime(new Date());
        comBo.setCreateBy(userComponent.getCurrentUser(LoginTypeEnums.WEB.getType()).getUserId().toString());
        save(comBo);

        for(Long menuId : refMenuTempPojo.getMenuIdList()){
            comboDetailDao.insert(ComboDetail.builder().comboId(comBo.getId()).menuId(menuId).build());
        }
        return null;
    }

    @Override
    public String modifyTemp(ComboPojo comboPojo) {
        String checkRes = checkUnion(comboPojo);
        if(StringUtils.isNotEmpty(checkRes)){
            return checkRes;
        }
        if(CollectionUtils.isEmpty(comboPojo.getMenuIdList())){
            return "未配置菜单";
        }
        ComBo comBo = comboPojo.pojoTo();
        comBo.setUpdateBy(userComponent.getCurrentUser(LoginTypeEnums.WEB.getType()).getUserId().toString());
        comBo.setUpdateTime(new Date());
        updateById(comBo);

        //清空详情
        comboDetailDao.deleteByComboId(comboPojo.getId());
        for(Long menuId : comboPojo.getMenuIdList()){
            comboDetailDao.insert(ComboDetail.builder().comboId(comBo.getId()).menuId(menuId).build());
        }

        return null;
    }

    @Override
    public String deleteById(Long id,Boolean sureDelete) {
        if(sureDelete){
            removeById(id);
            comboDetailDao.deleteByComboId(id);
            return null;
        }

        LambdaQueryWrapper<ComboDetail> query = new LambdaQueryWrapper<>();
        query.eq(ComboDetail::getComboId,id);
        long count = comboDetailDao.selectCount(query);
        if(count > 0){
            return "套餐存在内容，是否确认删除";
        }
        removeById(id);
        return null;
    }

    @Override
    public List<Menu> listComboDetail(Long comBoId) {
        if( comBoId == null &&  userComponent.getCurrentUser(LoginTypeEnums.WEB.getType()).getUserType() - UserTypeEnums.SYSTEM.getUserType() == 0){
            List<Menu>  menuList = menuDao.selectList(null);
            menuList.sort((o1,o2) -> o1.getOrderNum() - o2.getOrderNum());
            return menuList;
        }

        List<ComboDetail> comboDetailList = comboDetailDao.selectList(ComboDetail.builder().comboId(comBoId).build().query());
        if(CollectionUtils.isEmpty(comboDetailList)){
            return new ArrayList<>();
        }
        List<Menu>  menuList = SplitUtil.runSplit(500,comboDetailList.stream().map(ComboDetail::getMenuId).collect(Collectors.toList()),
                ids -> menuDao.selectByIdList(ids));
        menuList.sort((o1,o2) -> o1.getOrderNum() - o2.getOrderNum());
        return menuList;
    }


    /**
     * 查重
     * @param comboPojo
     * @return
     */
    private String checkUnion(ComboPojo comboPojo){
        //判断
        LambdaQueryWrapper<ComBo> query = new LambdaQueryWrapper<>();
        query.ne(comboPojo.getId() != null,ComBo::getId,comboPojo.getId());
        query.eq(ComBo::getComboCode,comboPojo.getComboCode());
        query.eq(ComBo::getComboLevel,comboPojo.getComboLevel());
        long counts = count(query);
        if(counts > 0){
            return "该等级套餐已经存在";
        }
        return null;
    }

    private List<ComBo> compliteCount(List<ComBo>  list){
        if(CollectionUtils.isEmpty(list)){
            return list;
        }
        //1查询详情
        List<Long> comBoIdList = list.stream().map(ComBo::getId).collect(Collectors.toList());
        LambdaQueryWrapper<ComboDetail> query = new LambdaQueryWrapper<>();
        query.in(ComboDetail::getComboId,comBoIdList);
        List<ComboDetail> detailList = comboDetailDao.selectList(query);
        Map<Long,List<ComboDetail>>  comBoIdMap =  detailList.stream().collect(Collectors.groupingBy(ComboDetail::getComboId));


        list.forEach(o->{
            Integer counts = 0;
            if(comBoIdMap.get(o.getId()) != null) {
                counts = comBoIdMap.get(o.getId()).size();
            }
          o.setMenuCounts(counts);
        });
        return list;
    }
}
